package com.wyzz.hr.bo.impl;

import freemarker.template.*;
import java.io.*;
import java.util.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.wyzz.hr.bo.TemplateService;
import com.wyzz.hr.util.Environment;

public class TemplateServiceFreeMarkerImpl implements TemplateService {

	public TemplateServiceFreeMarkerImpl() {
	}

	public void setTemplateFilePath(String templateFilePath) {
		this.templateFilePath = templateFilePath;
	}

	public void setSupportedVariables(Map supportedVariables) {
		this.supportedVariables = supportedVariables;
	}

	public void setFreemarkerSettings(Properties freemarkerSettings) {
		this.freemarkerSettings = freemarkerSettings;
	}

	public String getContent(String templateName, Map model) {
		String mailURL = StringUtils.defaultIfEmpty((String) model.get("URL"),
				"");
		String sysURL = (String) supportedVariables.get("URL");
		model.put("URL", (new StringBuilder()).append(sysURL).append(mailURL)
				.toString());
		model.put("APPROVEURL", (new StringBuilder()).append(sysURL).append(
				StringUtils
						.defaultIfEmpty((String) model.get("APPROVEURL"), ""))
				.toString());
		try {
			Template textTemplate = createConfiguration("email").getTemplate(
					(new StringBuilder()).append(templateName).append(".ftl")
							.toString());
			StringWriter textWriter = new StringWriter();
			textTemplate.process(model, textWriter);
			return textWriter.toString();
		} catch (IOException e) {
			logger.warn((new StringBuilder()).append(
					"\u627E\u4E0D\u5230\u6A21\u677F\u6587\u4EF6").append(
					templateName).toString());
			e.printStackTrace();
		} catch (TemplateException e) {
			logger.warn((new StringBuilder()).append(
					"\u53C2\u6570\u4F20\u9012\u9519\u8BEF")
					.append(templateName).toString());
			e.printStackTrace();
		}
		return "";
	}

	public Configuration createConfiguration(String type)
			throws TemplateException, IOException {
		if ("email".equals(type)) {
			if (emailConfiguration == null) {
				emailConfiguration = new Configuration();
				emailConfiguration.setSettings(freemarkerSettings);
				emailConfiguration.setObjectWrapper(new DefaultObjectWrapper());
				String key;
				for (Iterator it = supportedVariables.keySet().iterator(); it
						.hasNext(); emailConfiguration.setSharedVariable(key,
						supportedVariables.get(key)))
					key = (String) it.next();
				String filePath = Environment.getEmailTemplateHome();
				emailConfiguration.setDirectoryForTemplateLoading(new File(
						filePath));
			}
			return emailConfiguration;
		}
		if ("pdf".equals(type)) {
			if (pdfConfiguration == null) {
				pdfConfiguration = new Configuration();
				pdfConfiguration.setSettings(freemarkerSettings);
				pdfConfiguration.setObjectWrapper(new DefaultObjectWrapper());
				String key;
				for (Iterator it = supportedVariables.keySet().iterator(); it
						.hasNext(); pdfConfiguration.setSharedVariable(key,
						supportedVariables.get(key)))
					key = (String) it.next();
				String filePath = Environment.getPDFTemplateHome();
				pdfConfiguration.setDirectoryForTemplateLoading(new File(
						filePath));
			}
			return pdfConfiguration;
		} else {
			return null;
		}
	}

	public String getPDFContent(String templateName, Map model) {
		try {
			Template textTemplate = createConfiguration("pdf").getTemplate(
					(new StringBuilder()).append(templateName).append(".ftl")
							.toString());
			StringWriter textWriter = new StringWriter();
			textTemplate.process(model, textWriter);
			return textWriter.toString();
		} catch (IOException e) {
			logger.warn((new StringBuilder()).append(
					"\u627E\u4E0D\u5230\u6A21\u677F\u6587\u4EF6").append(
					templateName).toString());
			e.printStackTrace();
		} catch (TemplateException e) {
			logger.warn((new StringBuilder()).append(
					"\u53C2\u6570\u4F20\u9012\u9519\u8BEF")
					.append(templateName).toString());
			e.printStackTrace();
		}
		return "";
	}

	public boolean checkPDFTemplateExist(String templateName) {
		String templateFile = (new StringBuilder()).append(
				Environment.getPDFTemplateHome()).append(templateName).append(
				".ftl").toString();
		System.out.println(templateFile);
		File file = new File(templateFile);
		return file.exists();
	}

	public void doTemplateCopy(String fromFolder, String toFolder) {
		File custFolder = new File(toFolder);
		custFolder.mkdirs();
		File standardTemplateFolder = new File(fromFolder);
		File standardTemplates[] = standardTemplateFolder
				.listFiles(new FileFilter() {

					public boolean accept(File pathname) {
						return pathname.getName().endsWith(".ftl");
					}
				});
		for (int i = 0; i < standardTemplates.length;) {
			String templateName = standardTemplates[i].getName();
			if ((new File(custFolder, templateName)).exists())
				continue;
			try {
				logger.info((new StringBuilder()).append("Copy template:")
						.append(standardTemplates[i].getName()).toString());
				FileUtils.copyFileToDirectory(standardTemplates[i], custFolder);
				continue;
			} catch (IOException e) {
				logger.error((new StringBuilder()).append(
						"\u590D\u5236\u6A21\u677F")
						.append(standardTemplates[i]).append(
								"\u65F6\u53D1\u751F\u9519\u8BEF:").append(
								e.getMessage()).toString());
				e.printStackTrace();
				i++;
			}
		}

	}

	public String getTemplateContent(String templateFileName) {
		File file = new File((new StringBuilder()).append(
				Environment.getEmailTemplateHome()).append(templateFileName)
				.toString());
		try {
			return FileUtils.readFileToString(file, "utf-8");
		} catch (IOException e) {
			logger.warn((new StringBuilder()).append(
					"\u8BFB\u53D6\u6A21\u677F\u6587\u4EF6").append(
					templateFileName).append("\u65F6\u53D1\u751F\u9519\u8BEF:")
					.append(e.getMessage()).toString());
			e.printStackTrace();
			return "";
		}
	}

	public String modifyTemplateContent(String templateFileName, String content) {
		File file = new File((new StringBuilder()).append(
				Environment.getEmailTemplateHome()).append(templateFileName)
				.toString());
		try {
			FileUtils.writeStringToFile(file, content, "utf-8");
		} catch (IOException e) {
			String error = (new StringBuilder()).append(
					"\u5199\u6A21\u677F\u6587\u4EF6").append(templateFileName)
					.append("\u65F6\u53D1\u751F\u9519\u8BEF:").append(
							e.getMessage()).toString();
			logger.warn(error);
			return error;
		}
		return null;
	}

	public void createTemplate(String content, String fullPath)
			throws IOException {
		File file = new File(fullPath);
		FileUtils.writeStringToFile(file, content, "utf-8");
	}

	public String getTemplateFilePath() {
		return templateFilePath;
	}

	public void deleteTemplate(String fileName) {
		try {
			FileUtils.forceDelete(new File(fileName));
		} catch (IOException e) {
		}
	}

	public Configuration getEmailConfiguration() {
		return emailConfiguration;
	}

	public void setEmailConfiguration(Configuration emailConfiguration) {
		this.emailConfiguration = emailConfiguration;
	}

	public Configuration getPdfConfiguration() {
		return pdfConfiguration;
	}

	public void setPdfConfiguration(Configuration pdfConfiguration) {
		this.pdfConfiguration = pdfConfiguration;
	}

	private static final Logger logger = Logger
			.getLogger(com.wyzz.hr.bo.impl.TemplateServiceFreeMarkerImpl.class);
	private Configuration emailConfiguration;
	private Configuration pdfConfiguration;
	private Map supportedVariables;
	private Properties freemarkerSettings;
	private String templateFilePath;

}
